/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package overfeatfeatureextraction;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 *
 * @author mwh
 */
public class Controller {

    public static void main(String[] args) throws Exception {
        Controller c = new Controller();
        c.start();
    }
    public static int batchSize = 10;
    public static int sleepSeconds = 30;
    public static String imageDir = "/tmp/overfeatimages";

    public void start() throws IOException, DecoderException, InterruptedException {

        HBaseGetter hbaseGetter = new HBaseGetter();
        HBaseResultPutter hbaseResultsPutter = new HBaseResultPutter();

        while (true) {
            List<AvroImage> images = new ArrayList<>();
            List<byte[]> keys = hbaseGetter.get(batchSize, images);
            System.err.println("Retrieved " + keys.size() + " images for processing\t" + images.size());
            if (keys.isEmpty()) {
                System.err.println("Sleeping for " + sleepSeconds + " sec");
                Thread.sleep(sleepSeconds * 1000);
            }

            writeImagesToDisc(imageDir, images);
            Map<String, ImageResult> results = OverFeatFeatureExtraction.extractDir(imageDir);

            for (Map.Entry<String, ImageResult> e : results.entrySet()) {
                hbaseResultsPutter.put(e.getKey(), e.getValue());
            }

            // If we get to this point we assume that all was ok,
            // so we delete key from the 'imagefailed' table
            hbaseGetter.deleteFromTable(keys, hbaseGetter.failedTable);
        }
    }

    public static void writeImagesToDisc(String dir, List<AvroImage> images) throws IOException {

        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdir();
        }
        FileUtils.cleanDirectory(dirFile);

        for (AvroImage image : images) {
            byte[] md5 = image.getMd5().array();
            String md5Str = Hex.encodeHexString(md5);
            String fn = md5Str + ".png";
            File imageFile = new File(dirFile, fn);
            OutputStream os = new FileOutputStream(imageFile);
            IOUtils.write(image.getContent().array(), os);
            os.close();

        }
    }
}
